package service

import (
	"fmt"
	"net/http"

	"github.com/gin-gonic/gin"

	"github.com/lzppppppp/virapaksa-go/internal/system_monitor/model"
	"github.com/lzppppppp/virapaksa-go/internal/system_monitor/repository"
	gmidwa "github.com/lzppppppp/virapaksa-go/pkg/middleware"
	"github.com/spf13/viper"
)

// 推送agent
func PushAgent(context *gin.Context) {

	type NodePushAgentData struct {
		Hostname string
		IP       string
		Type     string
		AppTeam  string
	}
	param := []NodePushAgentData{}
	err := context.BindJSON(&param) // 接收前端数据
	if err != nil {
		context.JSON(500, gin.H{"err": err})
		return
	}

	funcVar := gmidwa.FuncVar{ // 获取配置文件中的awx信息
		IP:    viper.GetString("awx.server.ip"),
		Port:  viper.GetString("awx.server.port"),
		Token: viper.GetString("awx.server.token"),
	}

	DB := repository.GetDB()

	dc2dc := map[string]string{
		"北京数据中心":    "pek",
		"内蒙数据中心":    "nm",
		"上海数据中心":    "sh",
		"合肥数据中心":    "hf",
		"内蒙数据中心-和林": "nm",
	}

	nodeAwxHost := make(map[string][]gmidwa.AwxHostVar) // 储存不同的数据中心对应的分区和变量
	for _, value := range param {
		var data []model.CmdbAllServer
		DB.Table("cmdb_all_servers").Where("ip = ? AND hostname = ?", value.IP, value.Hostname).Find(&data)
		nodeAwxHostVar := gmidwa.AwxHostVar{
			IP: value.IP,
		}
		dc := dc2dc[data[0].Datacenter]
		nodeAwxHost[dc] = append(nodeAwxHost[dc], nodeAwxHostVar)
	}
	fmt.Println("nodeAwxHost", nodeAwxHost)
	for key := range nodeAwxHost { // 根据数据中心，推送agent

		funcAwxLaunch := gmidwa.FuncAwxLaunch{
			Tags:       param[0].Type,
			DataCenter: key,
			Env:        "sc",
			Host:       nodeAwxHost[key],
		}
		if param[0].Type == "bdops" { // 如果是bdops，则选择对应的template和appteam
			funcAwxLaunch.Type = viper.GetString("awx.name.job_template.bdops")
			funcAwxLaunch.AppTeam = param[0].AppTeam
		} else {
			funcAwxLaunch.Type = viper.GetString("awx.name.job_template.exporter")
		}

		awxConfigInfo := gmidwa.AwxConfigInfo{
			InstanceGrouId: viper.GetInt("awx.id.instance_group." + key),
			EnvID:          viper.GetString("awx.env.sc"),
			CredentialId:   viper.GetInt("awx.id.credential." + key),
		}

		var a = gmidwa.CallAwx{
			FuncVar:       funcVar,
			AwxConfigInfo: awxConfigInfo,
		}

		jobID := a.LaunchJobforMonitorApply(funcAwxLaunch)
		fmt.Println(jobID)
	}

	type jsonData struct {
		Code int
		Data string
	}
	data := jsonData{
		Code: 200,
		Data: "success",
	}
	context.JSON(http.StatusOK, data)
}
